import QtQuick
import com.example.tray 1.0
import com.example.localConfig 1.0
import com.example.remoteDataBase 1.0
import com.example.localDataBase 1.0
import QtQuick.Controls
import QtQuick.Window
import QtMultimedia
import QtNetwork

ApplicationWindow {
    id:root
    property int userId:-1//用户ID
    property int experience: 0//经验
    property int level: 0//等级
    property int immortalClass: 1//等级
    property int photo//头像照片
    property string userName//用户名称
    property var stickyNoteWindow//便签窗口
    property int idFrom:-1//聊天对象的ID
    //property int idTo
    property bool cMReceived: false//聊天消息已经接收
    property bool cMSended: false//聊天消息已经发送
    property int commandLevel: 0//命令层级
    property int commandId: 0//当前执行命令ID
    property int linggen:0//灵根

    visible: true
    x:Screen.width-150
    y:Screen.height-150
    width: 100
    height: 100
    flags: Qt.FramelessWindowHint |Qt.WindowStaysOnTopHint//窗口无标题栏和在最前端
    color:"#00000000"
    title: "Experience Life"
    SystemTray {
        id:systemTray
        onIconClicked:{//点击系统托盘图标，显示或隐藏主窗口
            if(root.visibility==2)root.hide()
            else root.show()            //window.show() window.raise() window.requestActivate()
        }
        onIconDoubleClicked:{//点击系统托盘图标，显示或隐藏主窗口
            localConfig.writeLocalConfig("clipboard",0)
            localConfig.writeLocalConfig("stickynote",0)
            localConfig.writeLocalConfig("chatmessage",0)
            localConfig.writeLocalConfig("ID",-1)
            localConfig.writeLocalConfig("password","")
            localConfig.writeLocalConfig("username","")
            userId=-1
            userName=""
        }
        onTOffClipboardClicked:{//隐藏消息窗口
            windowClipboard.hide()
            listViewCB.visible=false
            playerStatus.visible=false
            wCMWindow.visible=false
            root.experience++
        }
        onNewStickyNoteClicked:{//新建便签
            if(userId>0){
                root.experience+=5
                var component = Qt.createComponent("NewStickyNote.qml")//创建新窗口
                var NewStickyNoteWindow = component.createObject(root)
                NewStickyNoteWindow.show()
                windowClipboard.visible=false
            }else {modelListViewCB.append({"textclipboard":"请先登录或注册"});windowClipboard.visible=true}
        }
        onOpenStickyNoteWallClicked:{//打开便签墙
            if(userId>0){
                root.experience++
                if(root.stickyNoteWindow==undefined){
                    var component = Qt.createComponent("StickyNote.qml")//创建新窗口
                    root.stickyNoteWindow = component.createObject(root)
                    root.stickyNoteWindow.show()
                }else if(root.stickyNoteWindow.visible)root.stickyNoteWindow.visible=false
                else root.stickyNoteWindow.visible=true
            }else {modelListViewCB.append({"textclipboard":"请先登录或注册"});windowClipboard.visible=true}
        }
        onSearchPartnerClicked: {//开启聊天窗口
            root.experience+=5
            wCMWindow.visible=true
            //remoteDB.sendChatMessage(userId,"message")
        }
    }
    LocalConfig{//本地设置config.ini
        id:localConfig
    }
    RemoteDataBase{//远程数据访问类
        id:remoteDB
        onUserReceived:function(message,users) {//接收用户信息,用户登录
            if (users && users.length > 0) { // 检查 users 是否有效
                var tuser = users[0]// tuser 是一个 JavaScript 对象
                root.userId=tuser.id
                root.userName=tuser.name
                root.experience=parseInt(tuser.experience)
                root.level=parseInt(tuser.level)
                root.immortalClass=parseInt(tuser.immortalclass)
                root.photo=parseInt(tuser.photo)
                root.linggen=parseInt(tuser.linggen)
                systemTray.setUserPhoto(root.photo)
            }else{
                root.userId=-1
            }
        }
        onChatMessageReceived: function(chatMessage){
            wCMWindow.visible=true
            if (chatMessage && chatMessage.length > 0) { // 检查 users 是否有效
                timerChatAnswer.stop()
                timerExperience.interval=10000
                for(var i=0;i<chatMessage.length;i++){
                    var tMessage = chatMessage[i]// tuser 是一个 JavaScript 对象
                    root.cMReceived=true//已经收到答复消息
                    root.cMSended=false
                    timerChatInterval.restart()//从新计时聊天间隔
                    root.idFrom=tMessage[1]
                    if(tMessage[4]=="blank")modelListMessage.append({"textMessage":root.idFrom+"向你打招呼S"})
                    else modelListMessage.append({"textMessage":tMessage[4]+"R"})
                    localConfig.writeLocalConfig("chatmessage",(parseInt(localConfig.readLocalConfig("chatmessage")) + 1).toString())
                    listMessage.positionViewAtEnd()
                }
            }
        }
        onResponseReceived: {//deepseek消息接收
            modelListMessage.append({"textMessage": response + "R"});
            listMessage.positionViewAtEnd()
            wCMWindow.visible = true;
            timerChatAnswer.interval = 10000;
            root.cMReceived=true//已经收到答复消息
            root.cMSended=false
        }
    }
    LocalDataBase{
        id:localDB
    }
    Rectangle{
        id:mainWindow
        width:parent.width
        height:parent.height
        visible: true
        color:"#00000000"
        Image {
            id: image
            width: parent.width
            height: parent.height
            source: photo>1 ?"image.png":"image2.png"
            MouseArea
            {
                anchors.fill: parent
                hoverEnabled:true
                property int dragx//拖拽x坐标
                property int dragy//拖拽y坐标
                property bool draging//是否拖拽
                property int rootx//根窗口x
                property int rooty//根窗口y
                onPressed:
                {
                    dragx=mouseX
                    dragy=mouseY
                    draging=true
                    rootx=root.x
                    rooty=root.y
                }
                onReleased:
                {
                    draging=false
                    if(Math.abs(root.x-rootx)<10&&Math.abs(root.y-rooty)<10){
                        if(mouseX>mouseY&&mouseX+mouseY<100){
                            if(windowClipboard.visibility==2){
                                listViewCB.visible=true
                                playerStatus.visible=false
                                windowClipboard.hide()
                            }
                            else{
                                windowClipboard.show()
                                listViewCB.visible=false
                                playerStatus.visible=true
                                myTimer.start()
                            }
                        }
                        if(mouseX>mouseY&&mouseX+mouseY>100){
                            if(windowClipboard.visibility==2)windowClipboard.hide()
                            else{
                                listViewCB.visible=true
                                playerStatus.visible=false
                                windowClipboard.show()
                            }
                            //windowClipboard.raise()将窗口提升到最前面windowClipboard.requestActivate() 请求激活窗
                        }
                        if(mouseX<mouseY&&mouseX+mouseY<100){
                            if(userId>0){
                                if(root.stickyNoteWindow==undefined){
                                    var component = Qt.createComponent("StickyNote.qml")//创建新窗口
                                    root.stickyNoteWindow = component.createObject(root)
                                    root.stickyNoteWindow.show()
                                }else if(root.stickyNoteWindow.visible)root.stickyNoteWindow.visible=false
                                else root.stickyNoteWindow.visible=true
                            }else {modelListViewCB.append({"textclipboard":"请先登录或注册"});windowClipboard.visible=true}
                        }
                        if(mouseX<mouseY&&mouseX+mouseY>100){
                            if(wCMWindow.visible)wCMWindow.visible=false
                            else wCMWindow.visible=true
                        }
                    }
                }
                onPositionChanged:
                {
                    if(draging)
                    {
                        root.x += mouseX-dragx
                        root.y += mouseY-dragy
                    }
                }
                onEntered:{
                    if(mouseX>mouseY&&mouseX+mouseY<100)toolTipImage.text="修行者的状态"
                    if(mouseX>mouseY&&mouseX+mouseY>100)toolTipImage.text="剪切板"
                    if(mouseX<mouseY&&mouseX+mouseY<100)toolTipImage.text="便利贴墙"
                    if(mouseX<mouseY&&mouseX+mouseY>100)toolTipImage.text="消息窗口"
                    toolTipImage.visible=true
                }
                onExited:{
                    toolTipImage.visible=false
                }
            }
            ToolTip{
                id:toolTipImage
                text: "ID"
                visible: false
                delay: 2000 // 可选：延迟显示时间(ms)
                anchors.centerIn: parent
            }

            // 使用 HoverHandler 来触发 ToolTip 显示
            HoverHandler {
                id: hoverHandler
            }
        }
    }
    Component.onCompleted:{
        userId=parseInt(localConfig.readLocalConfig("ID"))
        if(userId>0){
            userName=localConfig.readLocalConfig("username")
            remoteDB.userLoginAuto(userId,localConfig.readLocalConfig("password"))
            toolTipImage.text=userName+",你好!\n你的ID是"+userId

        }else{
            var component = Qt.createComponent("Welcome.qml")//创建新窗口
            var windowWelcome = component.createObject(root)
            windowWelcome.show()
        }
        timerExperience.start()
    }
    Window {//剪切板窗口
        id: windowClipboard
        property string lszfc
        x:root.x
        y:root.y-120
        visible: false
        width: 150
        height: 120
        flags: Qt.FramelessWindowHint |Qt.WindowStaysOnTopHint//窗口无标题栏和在最前端
        ListView{
            id:listViewCB
            width:parent.width
            height:parent.height
            model:modelListViewCB
            delegate:Text {
                anchors.left:parent.left
                color:"black"
                ToolTip.delay: 2000
                text:Qt.formatDateTime(new Date(), "HH:mm")+":"+textclipboard
                MouseArea{
                    anchors.fill: parent
                    //acceptedButtons:Qt.LeftButton | Qt.RightButton // 接受左键和右键
                    hoverEnabled:true
                    onClicked:{
                        windowClipboard.lszfc=modelListViewCB.get(index).textclipboard
                        clipboardHandler.setClipboardText(windowClipboard.lszfc)
                        //print(jqbwblb.get(index).textclipboard)
                    }
                    onDoubleClicked:{
                        var searchQuery =modelListViewCB.get(index).textclipboard
                        var url = "https://www.baidu.com/s?wd=" + encodeURIComponent(searchQuery)
                        Qt.openUrlExternally(url)
                    }
                    onEntered:{
                        parent.ToolTip.text=modelListViewCB.get(index).textclipboard
                        parent.ToolTip.visible=true
                    }
                    onExited:{
                        parent.ToolTip.visible=false
                    }
                }
            }
        }
        ListModel{
            id:modelListViewCB//剪切板文本列表
        }
        Component.onCompleted:{
            clipboardHandler.clipboardChanged.connect(function(text){
                if(windowClipboard.lszfc!==text&&text.length!==0){
                    modelListViewCB.append({"textclipboard":text})//显示列表
                    windowClipboard.lszfc=text//将文本临时储存
                    listViewCB.positionViewAtEnd()//滚到列表最末端
                    listViewCB.visible=true//列表设为可见
                    playerStatus.visible=false//玩家状态设为不可见
                    windowClipboard.visible=true//窗口设为可见
                    root.experience++//经验加1
                    myTimer.start()//显示倒计时
                    localConfig.log(text)//记录log文件
                    localConfig.writeLocalConfig("clipboard",(parseInt(localConfig.readLocalConfig("clipboard")) + 1).toString())
                }//连接C++消息槽
            })
        }
        Rectangle{//修仙状态
            id:playerStatus
            width:parent.width
            height:parent.height
            visible:false
            property string pcMessage
            Text {
                id: idAName
                font.pixelSize: 9
                text: userId>0 ? qsTr("ID："+root.userId+",昵称："+root.userName+"灵根："+root.linggen+"\n经验值："
                           +root.experience+",等级："+root.level+"\n修仙阶段："+localDB.readImmortalClass(immortalClass)):"您还没有登录！"
            }
            Text{
                id:nAnimationText
                y:60
                font.pixelSize: 20
                anchors.horizontalCenter:parent.horizontalCenter
                MouseArea{
                    id:nAnimationMouse
                    anchors.fill: parent
                    onClicked: {
                        nAnimationTimer.stop()
                        for(var i=0;i<5;i++){
                            if(nAnimationText.text[i*2]=="金")linggen+=1*Math.pow(10, i)
                            else if(nAnimationText.text[i*2]=="木")linggen+=2*Math.pow(10, i)
                            else if(nAnimationText.text[i*2]=="水")linggen+=3*Math.pow(10, i)
                            else if(nAnimationText.text[i*2]=="火")linggen+=4*Math.pow(10, i)
                            else if(nAnimationText.text[i*2]=="土")linggen+=5*Math.pow(10, i)
                        }
                        print(linggen)
                        localConfig.writeLocalConfig("linggen",linggen)
                        remoteDB.saveLinggen(userId,linggen)
                        nAnimationMouse.destroy()
                    }
                }
            }
        }
    }
    Timer {
        id: timerWarn
        interval: 20000 // 设置为1000毫秒 = 1秒
        running: false // 定时器启动时即开始计时
        repeat: false // 只触发一次
        onTriggered: {
            wCMWindow.visible=false
        }
    }
    Timer {
        id: timerChatAnswer
        interval: 600000 // 设置为1000毫秒 = 1秒,现设11分钟，后续增加
        running: false // 定时器启动时即开始计时
        repeat: false // 只触发一次
        onTriggered: {
            //和通义开聊
            sendRequest(wCMWindow.chatT)
            //remoteDB.sendRequest(wCMWindow.chatT)
        }
    }
    Timer {
        id: myTimer
        interval: 20000 // 设置为1000毫秒 = 1秒
        running: false // 定时器启动时即开始计时
        repeat: false // 只触发一次
        onTriggered: {
            windowClipboard.visible=false
        }
    }
    Timer {
        id: nAnimationTimer
        interval: 100 // 设置为1000毫秒 = 1秒
        running: false // 定时器启动时即开始计时
        repeat: true // 只触发一次
        onTriggered: {
            var stringt=""
            for(var i=0;i<5;i++){
                switch(Math.floor(Math.random()*5)){
                case 0:
                   stringt+="金 "
                    break;
                case 1:
                   stringt+="木 "
                    break;
                case 2:
                   stringt+="水 "
                    break;
                case 3:
                   stringt+="火 "
                    break;
                case 4:
                   stringt+="土 "
                    break;
                }
            }
            nAnimationText.text=stringt
        }
    }
    Timer {//聊天间隔30分钟后系统忘记聊天对象
        id: timerChatInterval
        interval: 1800000 // 设置为1000毫秒 = 1秒
        running: false // 定时器启动时即开始计时
        repeat: false // 只触发一次
        onTriggered: {
            idFrom=-1
            cMReceived=false
            cMSended=false
            timerChatAnswer.interval = 1800000;
            timerExperience.interval=60000
            modelListMessage.append({"textMessage":"聊天间隔超时，聊天对象丢失！S"})
        }
    }
    Timer {//升级及经验值增加
        id: timerExperience
        interval: 60000 // 设置为1000毫秒 = 1秒
        running: false // 定时器启动时即开始计时
        repeat: true // 只触发一次
        onTriggered: {
            root.experience++
            if(immortalClass<1){
                experience=0
                idAName.text="ID："+root.userId+",昵称："+root.userName+"\n修仙阶段：一介凡人\n想修仙，请在消息窗口键入'@我要修仙'"
            }
            if(root.experience>(Math.pow(1.5,root.level)*100-100))root.level++
            //print(experience+"-"+level)
            if(userId>0)remoteDB.saveExperience(userId,experience,level,immortalClass)
        }
    }
    Window {//聊天提醒消息窗口
        id:wCMWindow
        x:root.x-240
        y:root.y-240
        width: 240
        height: 320
        visible: false
        title: "聊天提醒"
        flags: Qt.FramelessWindowHint
        property string chatT
        ListView{
            id:listMessage
            width:parent.width
            height:parent.height
            model:modelListMessage
            delegate:Text {
                width:Math.min(implicitWidth,parent.width)
                property bool alignCenter: textMessage.slice(-1)==="S"
                property bool alignRight: textMessage.slice(-1)==="U"
                property bool alignLeft: textMessage.slice(-1)==="R"
                anchors.rightMargin: 5
                anchors.leftMargin: 5
                anchors.horizontalCenter: alignCenter ? parent.horizontalCenter:undefined
                anchors.right: alignRight ? parent.right : undefined
                anchors.left: alignLeft ? parent.left : undefined
                color:alignCenter ? "gray":"black"
                //selectByMouse: true  // 允许通过鼠标选择文本
                //padding:1
                wrapMode: Text.Wrap
                text:textMessage.substring(0, textMessage.length - 1)//Qt.formatDateTime(new Date(), "HH:mm")+":"+
                Rectangle {
                        anchors.fill: parent
                        color: alignCenter ? "white":"wheat"
                        z: -1  // 确保在文本下方
                        radius: 3
                    }
                MouseArea{
                    anchors.fill: parent
                    onClicked: {
                        localConfig.log(textMessage)//记录log文件
                    }
                }
            }
        }
        TextField {
            width:parent.width
            height: 25
            anchors.bottom:parent.bottom
            id: textInput
            placeholderText:"请输入要说的话"
            font.pixelSize: 15
            onAccepted: {
                if(userId>0)chatMessageSend()
                else modelListMessage.append({"textMessage":"请登录或注册S"})
            }
        }
        Button {
            anchors.bottom:parent.bottom
            anchors.right:parent.right
            text: qsTr("提交")
            onClicked:{
                if(userId>0)chatMessageSend()
                else modelListMessage.append({"textMessage":"请登录或注册S"})
            }
        }

        ListModel{
            id:modelListMessage//剪切板文本列表
        }

        Repeater{//便签提醒计时器
            id:warnR
            model: localConfig.readLocalConfig("warnchecked") ? localDB.readWarnTimeSN(root.userId): undefined//提醒时间列表
            Item {
                id: nameItem
                Timer{
                    property bool expire: modelData.timewarn-new Date().getTime()>0
                    interval: expire ? modelData.timewarn-new Date().getTime() : 100// 设置为1000毫秒 = 1秒
                    running: true // 定时器启动时即开始计时
                    repeat: false // 只触发一次
                    onTriggered: {
                        modelListMessage.append({"textMessage":Qt.formatDateTime(new Date(modelData.timewarn), "MM月dd日第")+modelData.id+"号提醒S"})
                        modelListMessage.append({"textMessage":"提醒内容："+modelData.sncontent})
                        listMessage.positionViewAtEnd()
                        wCMWindow.visible=true
                        wCMWindow.requestActivate()
                        wCMWindow.raise()
                        ring.play()
                        timerWarn.start()
                    }
                }
            }
        }
        SoundEffect{//快速反应音效MediaPlayer长声音
            id:ring
            source:"Ring.wav"
            volume:1 // 音量范围从 0 到 1
        }
    }
    function chatMessageSend():bool{
        if(!cMReceived&&cMSended){
            modelListMessage.append({"textMessage":"请不要重复发送消息！S"})
            listMessage.positionViewAtEnd()
        }else if(textInput.text.substring(0,1)==="@"){
            commandSend(textInput.text.substring(1, textInput.text.length))
        }else if(!cMSended){
            remoteDB.sendChatMessage(userId,idFrom,textInput.text)
            modelListMessage.append({"textMessage":textInput.text+"U"})//列表添加信息
            listMessage.positionViewAtEnd()//滚到列表最末端
            wCMWindow.chatT=textInput.text//将文本临时储存
            timerChatAnswer.start()//10分钟后启动通义聊天
            timerWarn.start()//显示倒计时
            cMSended=true//消息已发出
            cMReceived=false//未收到消息
            timerChatInterval.start()//半小时无消息清空开始计时
            print("Message has send:"+textInput.text)
            textInput.text=""//清空输入文本框
        }
        return true
    }
    function sendRequest(inputString:string){//通义千问提供代码
        var apiKey = "sk-53679796a11146fbac27cc8b0a380a1e"; // 使用你提供的有效API Key
        var apiUrl = "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions"; // 确保这是正确的API URL

        var xhr = new XMLHttpRequest();
        xhr.open("POST", apiUrl, true);

        // 设置Authorization头，确保没有多余的空格或其他字符
        xhr.setRequestHeader("Authorization", "Bearer " + apiKey.trim());
        xhr.setRequestHeader("Content-Type", "application/json");

        xhr.onreadystatechange = function() {
            if (xhr.readyState === XMLHttpRequest.DONE) {
                if (xhr.status === 200) {
                    try {
                        var response = JSON.parse(xhr.responseText);
                        var outputT = response.choices[0].message.content; // 假设返回的结果在output.text中
                        modelListMessage.append({"textMessage": outputT + "R"});
                        listMessage.positionViewAtEnd()//滚到列表最末端
                        wCMWindow.visible = true;
                        timerChatAnswer.interval = 10000;//将消息更新周期设为10秒
                        root.cMReceived=true//已经收到答复消息
                        root.cMSended=false
                        timerChatInterval.restart()//半小时无消息清空重新计时
                        timerWarn.stop()//显示倒计时停止
                    } catch (e) {
                        console.error("Error parsing JSON:", e);
                    }
                } else {
                    console.error("Error Response:", xhr.responseText);
                    outputT = "请求失败：" + xhr.status + "\n" + xhr.responseText;
                }
            }
        };

        // 确保prompt或messages字段正确，这里假设你需要发送的消息存储在wCMWindow.chatT中
        var data = JSON.stringify({
            model: "qwen-plus",
            //task: "generate",
            messages: [
                { "role": "user", "content": inputString}
            ]
        });

        // 打印请求体以便调试
        console.log("Request Body:", data);

        xhr.send(data);
    }
    function sendRequestC(inputString:string){//通义千问提供代码
        var apiKey = "sk-53679796a11146fbac27cc8b0a380a1e"; // 使用你提供的有效API Key
        var apiUrl = "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions"; // 确保这是正确的API URL

        var xhr = new XMLHttpRequest();
        xhr.open("POST", apiUrl, true);

        // 设置Authorization头，确保没有多余的空格或其他字符
        xhr.setRequestHeader("Authorization", "Bearer " + apiKey.trim());
        xhr.setRequestHeader("Content-Type", "application/json");

        xhr.onreadystatechange = function() {
            if (xhr.readyState === XMLHttpRequest.DONE) {
                if (xhr.status === 200) {
                    try {
                        var response = JSON.parse(xhr.responseText);
                        var outputT = response.choices[0].message.content; // 假设返回的结果在output.text中
                        /*modelListMessage.append({"textMessage": outputT + "R"});
                        listMessage.positionViewAtEnd()//滚到列表最末端
                        wCMWindow.visible = true;
                        timerChatAnswer.interval = 10000;//将消息更新周期设为10秒
                        root.cMReceived=true//已经收到答复消息
                        root.cMSended=false
                        timerChatInterval.restart()//半小时无消息清空重新计时
                        timerWarn.stop()//显示倒计时停止*/
                    } catch (e) {
                        console.error("Error parsing JSON:", e);
                    }
                } else {
                    console.error("Error Response:", xhr.responseText);
                    outputT = "请求失败：" + xhr.status + "\n" + xhr.responseText;
                }
            }
        };

        // 确保prompt或messages字段正确，这里假设你需要发送的消息存储在wCMWindow.chatT中
        var data = JSON.stringify({
            model: "qwen-plus",
            //task: "generate",
            messages: [
                { "role": "user", "content": inputString }
            ]
        });

        // 打印请求体以便调试
        console.log("Request Body:", data);

        xhr.send(data);
    }
    function commandSend(command:string):bool{//命令行指令解析
        var commandNameList=""
        var commandseded=false
        if(commandLevel==0){
            for(var i=1;i<=localDB.readCommandlistN();i++){
                var commandT=localDB.readCommand(i)
                commandNameList+=","+commandT[0].command
                if(commandT[0].command==command){
                    commandId=i
                    var prerequisiteId=localDB.readCPrerequisite(i)
                    if(prerequisiteId>0&&localConfig.readLocalConfig(commandT[0].condition)<1){
                        var commandP=localDB.readCommand(prerequisiteId)
                        modelListMessage.append({"textMessage": commandT[0].command+"之前，先要"+commandP[0].command + "S"});
                        listMessage.positionViewAtEnd()
                    }else{//如果有子项目展示所有子项目
                        var childrenC=localDB.readCChildrens(commandId)
                        if(childrenC.length>0){
                            modelListMessage.append({"textMessage":"您有以下选择：S"});
                            for(var j=0;j<childrenC.length;j++){
                                modelListMessage.append({"textMessage": (localDB.readCommand(childrenC[j].children))[0].command + "S"});
                            }
                        }
                        //modelListMessage.append({"textMessage": outputT + "R"});
                        //listMessage.positionViewAtEnd()//滚到列表最末端
                        print(childrenC[0].children)
                        doCommand()
                    }
                    commandseded=true
                }
            }
            if(!commandseded){
                var chatT="匹配'"+command+"'和'"+commandNameList+"'中的一条，不要过程及其他，只要结果"
                //sendRequestC(chatT)
            }
        }
    }
    function doCommand(){
        switch (commandId){
        case 7:
            if(root.linggen>0){
                modelListMessage.append({"textMessage": "你已经测过灵根了S"});
                listMessage.positionViewAtEnd()
            }else{
                windowClipboard.show()
                listViewCB.visible=false
                playerStatus.visible=true
                nAnimationTimer.start()
            }
            break;
        default:
        }
    }
}

/*function sendRequest() {//通义千问提供代码
    var apiKey = "sk-53679796a11146fbac27cc8b0a380a1e"; // 使用你提供的有效API Key
    var apiUrl = "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions"; // 确保这是正确的API URL

    var xhr = new XMLHttpRequest();
    xhr.open("POST", apiUrl, true);

    // 设置Authorization头，确保没有多余的空格或其他字符
    xhr.setRequestHeader("Authorization", "Bearer " + apiKey.trim());
    xhr.setRequestHeader("Content-Type", "application/json");

    xhr.onreadystatechange = function() {
        if (xhr.readyState === XMLHttpRequest.DONE) {
            if (xhr.status === 200) {
                try {
                    var response = JSON.parse(xhr.responseText);
                    var outputT = response.choices[0].message.content; // 假设返回的结果在output.text中
                    modelListMessage.append({"textMessage": outputT + "R"});
                    listMessage.positionViewAtEnd()//滚到列表最末端
                    wCMWindow.visible = true;
                    timerChatAnswer.interval = 10000;//将消息更新周期设为10秒
                    root.cMReceived=true//已经收到答复消息
                    root.cMSended=false
                    timerChatInterval.restart()//半小时无消息清空重新计时
                    timerWarn.stop()//显示倒计时停止
                } catch (e) {
                    console.error("Error parsing JSON:", e);
                }
            } else {
                console.error("Error Response:", xhr.responseText);
                outputT = "请求失败：" + xhr.status + "\n" + xhr.responseText;
            }
        }
    };

    // 确保prompt或messages字段正确，这里假设你需要发送的消息存储在wCMWindow.chatT中
    var data = JSON.stringify({
        model: "qwen-plus",
        //task: "generate",
        messages: [
            { "role": "user", "content": wCMWindow.chatT }
        ]
    });

    // 打印请求体以便调试
    console.log("Request Body:", data);

    xhr.send(data);
}*/

